/*
 * Amkai Enterprise Solution (AES.) 
 * Copyright 2004 by Amkai(TM), Inc.
 * www.amkai.com
 * 
 * Project: webservice
 * Package: com.amkai.aes.webservice.binary.sourcehandler
 * File: NewObjectHandler.java
 * Created: Oct 17, 2005 11:15:09 AM
 * Author: johnny 
 * 
 */
package com.amkai.aes.webservice.binary.objecthandler;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.homedns.mpetmaya.tools.LangUtil;

import com.amkai.aes.aescommon.service.binary.job.CreateNewObjectJob;
import com.amkai.aes.aescommon.service.result.IdResult;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.server.dictionary.DictionarySchedulingResourceManager;
import com.amkai.aes.server.dictionary.SharedDictionaryManager;
import com.amkai.aes.server.domaincommiter.dictionaryeditor.StateCodesCommiter;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.rad.designerbase.beans.RADBean;

/**
 * NewObjectHandler
 * @author johnny
 * Description:
 *
 */
public class NewObjectHandler implements JobObjectHandler<CreateNewObjectJob, RADBean, IdResult> {

	public IdResult process(CreateNewObjectJob job, RADBean object) throws Exception {
		SessionManager sm = SiteManager.Start();
		SharedDictionaryManager sdm = new SharedDictionaryManager(sm);
		IdResult result = new IdResult();
		try {
//			sm.openSession(LogInterceptor.newInstance(null,null, sm.getFactory().getSessionFactory()));
			sm.openSession();
			sm.openTransaction();
			
			Item item = LangUtil.as(Item.class, object);
			Serializable objectId = null;
			// KKORNEL: AES-4131 - Saving new item
			// KKORNEL: AES-11533
			if (item == null) {
				objectId = sm.saveV(object);
			} else {
				sdm.saveItem(item);
				// KKORNEL: AES-5778
				StateCodesCommiter.commitItemStateCodes(sm, item);
				objectId=item.getId();
			}

			result.setObjectId((Long)objectId);
			job.setObjectId(objectId);
			
			DictionarySchedulingResourceManager.executeSchedulingResourceUpdate(object, sm);
			sm.commitTransaction();
			
			if (item != null) {
				// KKORNEL: AES-11533
				sdm.activateAndCommitItem(item);
			}
		}
		catch (HibernateException he) {
			sm.rollbackTransaction();
			throw he;
		}
		finally {
			sm.closeSession();
		}
		return result;
	}
}
